package com.producter.service.impl;

import com.producter.dao.mapper.GoodMapper;
import com.producter.service.GoodService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class GoodServiceImpl implements GoodService {
    @Autowired
    GoodMapper goodMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    public static final String KEY="NUMS_KEY";
    public static final String LOCK_KEY="LOCK_KEY";
    @Override
    public int addNums() {
        log.info("addNums服务运行");
        redisTemplate.delete(KEY);
        int result=goodMapper.addNums();
        ExecutorService executorService= Executors.newFixedThreadPool(1);
        executorService.execute(()->{
            try {
                Thread.sleep(1000l);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            redisTemplate.delete(KEY);
        });
        return result;
    }

    @Override
    public int getNums() {
        log.info("getNums服务运行");
        Integer nums= (Integer) redisTemplate.opsForValue().get(KEY);
        if(nums!=null){
            return nums;
        }
        RLock rLock= redissonClient.getLock(LOCK_KEY);
        boolean islock=false;
        try {
            islock=rLock.tryLock(3,10, TimeUnit.SECONDS);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        if(islock){
            try {
                nums=(Integer) redisTemplate.opsForValue().get(KEY);
                if(nums!=null)
                    return  nums;
                nums=goodMapper.getNums();
                redisTemplate.opsForValue().set(KEY,nums,120,TimeUnit.MINUTES);
            }catch (Exception e){
                log.error("redis缓存错误：{}",e.getMessage());
            }finally {
                if (rLock.isLocked()) { // 是否还是锁定状态
                    if (rLock.isHeldByCurrentThread()) { // 时候是当前执行线程的锁
                        rLock.unlock(); // 释放锁
                    }
                }
            }
        }
        return nums;
    }
}
